document.addEventListener('DOMContentLoaded', () => {
  let clientIP = 'unknown';

  // 1) 先拿到用户 IP
  fetch('https://api.ipify.org?format=json')
    .then(res => res.json())
    .then(data => clientIP = data.ip)
    .catch(console.warn);

  // 2) 拉后端角色列表
  fetch('http://your_server_ip:2020/votes')
    .then(res => res.json())
    .then(data => {
      renderTable(data)
        .then(() => initDataTable());  // Only call initDataTable after table is fully rendered
    })
    .catch(console.error);

  async function renderTable(data) {
    const tbody = document.querySelector('#datatablesSimple tbody');
    tbody.innerHTML = ''; // Clear existing rows

    // Collect all characters and their images
    const items = [];
    const extensions = ['jpg', 'png', 'jpeg', 'webp'];

    for (let i = 1; i <= data.CharactersNum; i++) {
      const name = data[`Name_${i}`];
      const count = data[`Count_${i}`];

      let found = false;
      for (const ext of extensions) {
        const imgPath = `./Images/${name}.${ext}`;
        const img = new Image();
        img.src = imgPath;

        // Check if the image loads successfully (async)
        await new Promise((resolve) => {
          img.onload = () => {
            items.push({ name, count, imgPath });
            found = true;
            resolve();
          };
          img.onerror = () => resolve();
        });

        if (found) break; // If a valid image is found, break out of the loop
      }
    }

    // Create table rows (group by 2 items per row)
    const rows = [];
    for (let i = 0; i < items.length; i += 2) {
      const tr = document.createElement('tr');

      [0, 1].forEach(offset => {
        const item = items[i + offset];
        if (item) {
          const tdImg = document.createElement('td');
          const img = document.createElement('img');
          img.src = item.imgPath;
          img.alt = item.name;
          img.style.width = '60px';
          tdImg.appendChild(img);
          tr.appendChild(tdImg);

          const tdName = document.createElement('td');
          tdName.textContent = item.name;
          tr.appendChild(tdName);

          const tdCount = document.createElement('td');
          tdCount.textContent = item.count;
          tr.appendChild(tdCount);

          const tdBtn = document.createElement('td');
          const btn = document.createElement('button');
          btn.textContent = '投票';
          btn.classList.add('btn', 'btn-sm', 'btn-primary');
          btn.addEventListener('click', () => {
            const now = new Date();
            const time = `${now.getFullYear()}/${now.getMonth() + 1}/${now.getDate()}`;
            fetch('http://your_server_ip:2020/votecharactes', {
              method: 'POST',
              headers: { 'Content-Type': 'application/json' },
              body: JSON.stringify({
                username: clientIP,
                character: item.name,
                time
              })
            })
            .then(r => r.json())
            .then(resData => {
              const msgDiv = document.getElementById('message');
              msgDiv.textContent = resData.msg;
              msgDiv.style.color = resData.success === 'true' ? 'green' : 'red';
            });
          });
          tdBtn.appendChild(btn);
          tr.appendChild(tdBtn);
        } else {
          // Fill missing spots with empty cells
          for (let k = 0; k < 4; k++) {
            tr.appendChild(document.createElement('td'));
          }
        }
      });

      rows.push(tr);
    }

    // Append all rows at once
    tbody.append(...rows);
    return Promise.resolve(); // Indicate that rendering is complete
  }

  // 3) DataTable 初始化，必须放在 renderTable 之后、且只调用一次
  function initDataTable() {
    const tableEl = document.getElementById('datatablesSimple');
    // If DataTable is already initialized, destroy it first
    if (tableEl._dataTable) {
        tableEl._dataTable.destroy();
    }
    tableEl._dataTable = new simpleDatatables.DataTable(tableEl, {
        perPageSelect: [16, 24, 32, 40, 48],
        perPage: 16,
        layout: {
        top: '{select}{search}',   // Ensure the select dropdown is on the left side of the search box
        bottom: '{info}{pager}'
        },
        labels: {
        placeholder: "搜索 …",
        perPage: "{select} 条/页",
        noRows: "没有找到数据",
        info: "显示 {start} 到 {end}，共 {rows} 条"
        }
    });

    // 确保表头居中
    const headers = tableEl.querySelectorAll('th');
    headers.forEach(header => {
      header.style.textAlign = 'center';
    });
  }
});
